package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.ProcessPaidRecord;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author codingyz
 * @Description
 * @date 2025/3/30 15:03
 * @Version 1.0
 */
@Service("1002")
@Slf4j
public class TrackItemType implements ProcessPaidRecord {

    @Autowired
    private UserPaidTrackService userPaidTrackService;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Override
    public void processDiffItemTypePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        Long userId = userPaidRecordVo.getUserId();
        String orderNo = userPaidRecordVo.getOrderNo();
        String itemType = userPaidRecordVo.getItemType();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();

        // 1. 幂等性校验
        long count = userPaidTrackService.count(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getOrderNo, orderNo).eq(UserPaidTrack::getUserId, userId));
        if (count != 0) {
            // 已经存过了，直接返回
            log.error("该声音订单流水已经记录");
            return;
        }
        // 2. 保存订单流水
        // 2.1 查询声音对应的专辑id
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfoByTrackId(itemIdList.get(0));
        AlbumInfo albumInfoResultData = albumInfoResult.getData();
        if (albumInfoResultData == null) {
            log.error("远程调用album_service获取专辑信息失败");
            throw new GuiguException(201, "远程调用album_service获取专辑信息失败");
        }
        List<UserPaidTrack> userPaidTracks = new ArrayList<>();
        for (Long trackId : itemIdList) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(orderNo);
            userPaidTrack.setUserId(userId);
            userPaidTrack.setAlbumId(0L);
            userPaidTrack.setTrackId(trackId);
            userPaidTracks.add(userPaidTrack);
        }
        boolean b = userPaidTrackService.saveBatch(userPaidTracks);
        log.info("保存声音订单流水{}", b ? "失败" : "成功");
    }
}
